<template>
  <div>
    <el-button @click="addTreeNode">添加</el-button>
    <el-button @click="addMainTable">合计添加到主表</el-button>

<!--    <el-form ref="formRef" :model="form" :rules="rules">-->
    <el-form ref="formRef" v-model="form" :rules="rules">

      <el-form-item label="活动名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>

       <el-table
        :data="form.tableData"
        style="width: 100%;margin-bottom: 20px;"
        :summary-method="getSummaries"
        show-summary
        row-key="id"
        border
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column
          prop="wbsms"
          label="WBS描述"
          align="center"
          show-overflow-tooltip
          width="180">
      </el-table-column>
      <el-table-column
          prop="wbsys"
          label="WBS元素"
          align="left"
          show-overflow-tooltip
          width="180">
      </el-table-column>
      <el-table-column
          prop="fubm"
          label="服务编码"
          show-overflow-tooltip
          width="180">
      </el-table-column>
      <el-table-column
          prop="fwms"
          show-overflow-tooltip
          label="服务项描述"  min-width="200">
      </el-table-column>

<!--         <el-table-column
             label="合格" prop="num">
           <template slot-scope="scope">
             <el-form-item :prop="`tableData.${scope.$index}.num`"
                           :rules="[{
                                 validator:(rule, value, callback)=>validatorCom(rule, value, callback,scope.row,'num','notNum',scope.$index,'tableData',this)
                               }]">
               <el-input v-model="scope.row.num" clearable></el-input>
             </el-form-item>
           </template>
         </el-table-column>-->

      <el-table-column
          prop="estimate"
          width="120"
          align="center"
          label="订单金额">
        <template slot-scope="scope">
          <el-form-item :prop="`tableData.${scope.$index}.estimate`"
                        :rules="[{
                                 validator:(rule, value, callback)=>validatorCom(rule, value, callback,scope.row,'estimate','wchtje',scope.$index,'tableData',this)
                               }]">
              <el-input v-model="scope.row.estimate" v-if="!scope.row.children || scope.row.children.length == 0"></el-input> <!-- @blur="getNodeSum('estimate')"-->
              <span v-else>{{scope.row.estimate}}</span>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column
          prop="wchtje"
          width="120"
          align="center"
          label="完成合同金额">
        <template slot-scope="scope">
          <el-form-item :prop="`tableData.${scope.$index}.wchtje`"
                        :rules="[{
                                 validator:(rule, value, callback)=>validatorCom(rule, value, callback,scope.row,'estimate','wchtje',scope.$index,'tableData',this)
                               }]">
            <el-input v-model="scope.row.wchtje" v-if="!scope.row.children || scope.row.children.length == 0"  @blur="getNodeSum('wchtje')"></el-input>
            <span v-else>{{scope.row.wchtje}}</span>
          </el-form-item>

        </template>
      </el-table-column>
      <el-table-column
          prop="tzje"
          width="120"
          align="center"
          label="调整金额">
      </el-table-column>
      <el-table-column
          prop="tzsxsm"
          width="180"
          label="调整事项说明">
      </el-table-column>
      <el-table-column
          prop="gcxxjd"
          width="130"
          label="工程形象进度%">
        <template slot-scope="scope">
          {{calGcxxjd(scope.row)}}
        </template>
      </el-table-column>
      <el-table-column
          prop="zjqrje"
          width="110"
          label="造价确认金额">
      </el-table-column>
     <el-table-column
         prop="estimateCopy"
         width="120"
         align="center"
         label="订单金额Copy">
     </el-table-column>
      <el-table-column
          label="操作" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button @click="delTreeRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    </el-form>

    <treeDetail v-if="treeDetailVisible" ref="treeDetailRef" @sendSelectRow="getSelectRow" @close="close"></treeDetail>
  </div>
</template>

<script >
import {validatenull} from "@/utils/validate"
import treeDetail from "./treeDetail";
export default {
  components: {
    treeDetail
  },
  computed:{
    calGcxxjd(){
      return (row)=>{
        let value = ''
        if (!validatenull(row['wchtje']) &&  !validatenull(row['estimate']) && row["estimate"]!=0){
          value =Math.round((row['wchtje'] /row['estimate'])  * 10000 )  / 100
          this.$set(row,'gcxxjd',value)
          return value
        }else{
          this.$set(row,'gcxxjd','')
          return ''
        }
      }
    }
  },
 data(){
   return{
     treeDetailVisible:false,
     form:{
       name:'',
       tableData: [
       {
         wbsms:'（层级1）描述WBS描述WBS描述WBS描述WBS描述WBS', wbsys:'', fubm:'', fwms:'', estimate:'50',estimateCopy:'', wchtje:'', tzje:'', tzsxsm:'', gcxxjd:'', zjqrje:'',
         id: 3,
         date: '检索结果二.WBS描述3',
         name: '王小虎3',
         address: '上海市普陀区金沙江路 1519 弄',
         parentId:null,
         children: [{
           wbsms:'（层级1-1）', wbsys:'', fubm:'', fwms:'', wchtje:'', tzje:'', tzsxsm:'', gcxxjd:'', zjqrje:'',
           id: 31,
           parentId:3,
           estimate:'10',
           estimateCopy:'',
           children: [{
             wbsms: '（层级1-1-1）', wbsys: '', fubm: '', fwms: '', wchtje: '', tzje: '', tzsxsm: '', gcxxjd: '', zjqrje: '',
             id: 311,
             parentId: 31,
             estimate: '',
             estimateCopy:'',
           },{
             wbsms: '（层级1-1-2）', wbsys: '', fubm: '', fwms: '', wchtje: '', tzje: '', tzsxsm: '', gcxxjd: '', zjqrje: '',
             id: 312,
             parentId: 31,
             estimate: '',
             estimateCopy:'',
           }]
         },
           {
             wbsms:'（层级1-2）', wbsys:'', fubm:'', fwms:'', wchtje:'', tzje:'', tzsxsm:'', gcxxjd:'', zjqrje:'',
             id: 32,
             parentId:3,
             estimate:'',
             estimateCopy:'',
           }]
       },
       {
         wbsms:'（层级2）描述WBS描述WBS描述WBS描述WBS描述WBS', wbsys:'', fubm:'', fwms:'', estimate:'50',estimateCopy:'', wchtje:'', tzje:'', tzsxsm:'', gcxxjd:'', zjqrje:'',
         id:4,
         date: '检索结果二.WBS描述4',
         name: '王小虎44',
         address: '上海市普陀区金沙江路 1519 弄',
         parentId:null,
         children: [{
           wbsms:'（层级2-1）', wbsys:'', fubm:'', fwms:'', wchtje:'', tzje:'', tzsxsm:'', gcxxjd:'', zjqrje:'',
           id: 41,
           parentId:4,
           estimate:'', estimateCopy:'',
         },
           {
             wbsms:'（层级2-2）', wbsys:'', fubm:'', fwms:'', wchtje:'', tzje:'', tzsxsm:'', gcxxjd:'', zjqrje:'',
             id: 42,
             parentId:4,
             estimate:'', estimateCopy:'',
           }]
       }
     ],
     },
     tableDataOrigin:[],
     rules: {
       name: [
         {required: true, message: '请输入活动名称', trigger: 'blur'},
       ],
     },

     //三列的验证
     estimateValide:true, //订单金额
     wchtjeValide:true, //完成金额
     tzjeValide:true, //调整金额
   }
 },
  created() {
    this.tableDataOrigin = JSON.parse(JSON.stringify(this.form.tableData)) ;
  },
  methods:{
    addTreeNode(){
      this.treeDetailVisible = true ;
      this.markTreeAWithB(this.tableDataOrigin,this.treeToArray(this.form.tableData)) ;
      this.$nextTick(()=>{
        this.$refs.treeDetailRef.init(this.tableDataOrigin,JSON.parse(JSON.stringify(this.form.tableData))) ;
      })
    },
    //// 示例：删除ID为2的节点及其所有子节点
    // deleteNodeAndChildren(treeData, 2);
    deleteNodeAndChildren(treeData, nodeId) {
      // this.getNodeSum('wchtje') ;
      function deleteNode(nodes) {
        for (let i = 0; i < nodes.length; i++) {
          if (nodes[i].id === nodeId) {
            nodes.splice(i, 1);
            return true;
          }
          if (nodes[i].children && deleteNode(nodes[i].children)) {
            return true;
          }
        }
        return false;
      }
      return deleteNode(treeData);
    },
    delTreeRow(row){
      this.deleteNodeAndChildren(this.form.tableData,row.id)
      // this.form.tableData.splice(index, 1);
      this.getNodeSum('wchtje') //重新计算合同金额
      console.log('删除行后的表格重新计算:',this.form.tableData)
      // this.getNodeSum('tzje') //重新计算调整金额
      // this.getNodeSum('zjqrje') //重新计算造价金额
    },
    calculateTotalEmployees(node) {
      let total = Number(node.estimate) || 0;
      if (node.children) {
        node.children.forEach(child => {
          total += this.calculateTotalEmployees(child); // 使用组件的实例方法递归计算
        });
      }
      return total;
    },
    // getNodeSum(tableData){
    //   tableData.map(node => {
    //     node.estimate = this.calculateTotalEmployees(node); // 添加到每个节点中
    //     if (node.children){
    //       this.getNodeSum(node.children);
    //     }
    //   });
    // },
    getSelectRow(data){
      console.log("----:",data)
      // this.tableData[0].children.push(...data)
      // this.addToTree(this.tableData,data)
      if (!data) return ;
      let _this = this ;
      data.map(item=>{
        _this.addToTree(_this.form.tableData,item)
      })
    },
    close(){
      this.treeDetailVisible = false ;
    },
    markTreeAWithB(treeA, treeB) {
      // 辅助函数，用于查找id是否存在于B中
      function findInTreeB(id) {
        for (const item of treeB) {
          if (item.id == id) {
            return true;
          }
        }
        return false;
      }

      // 辅助函数，用于递归遍历和标记树A
      function traverseAndMark(node) {
        if (findInTreeB(node.id)) {
          node.disabled = true; // 如果在B中找到，标记为true
        } else {
          node.disabled = false; // 如果不在B中，标记为false，虽然这在某些情况下可能是多余的，取决于你的具体需求
        }
        if (node.children) {
          node.children.forEach(child => traverseAndMark(child)); // 递归处理子节点
        }
      }

      // 对树A进行遍历和标记
      treeA.forEach(node => traverseAndMark(node));

      console.log("treeA:",treeA)
    },
    /**
     * 数据扁平化
     * @param tree
     * @returns
     */
    treeToArray(tree) {
      let res = []
      for (const item of tree) {
        const { children, ...i } = item
        if (children && children.length) {
          res = res.concat(this.treeToArray(children))
        }
        res.push(i)
      }
      return res
    },
    addToTree(data,willInsertData) {
       data.map(item=>{
          //item.estimate = this.getSum(item.children) ;
          if (item.id == willInsertData.parentId){
             if (item.children){
               item.children.push(willInsertData);
             }else{
               item.children = [] ;
               item.children.push(willInsertData);
             }
          }
          if (item.children){
            this.addToTree(item.children,willInsertData);
          }
       })
    },
    getNodeSum(colProp){
      this.getNodeSum2(this.form.tableData,0,colProp)
    },
    getNodeSum2(tableData,sum,colProp) {
      tableData.map(item=>{
        if (item.children){
          const sumC = this.getNodeSum2(item.children,0,colProp)
          this.$set(item,colProp,sumC)
          sum += sumC
        }else{
          // sum +=  !item[colProp] ? 0 : Number(item[colProp])
          sum +=  !item[colProp] ? 0 :this.undefToZero(item[colProp])
        }
      })
      return sum;
    },
    //复制一列
    addCopyCol(array, childKey){
      if (!array || !array.length) return
      if (!childKey) childKey = "children"
      array.forEach((item) => {
        item.estimateCopy = item.estimate
        if (item[childKey] && item[childKey].length) {
          this.addCopyCol(item[childKey])
        }
      })
    },
    //加入验证列 对那列进行验证
    // estimateValide:true, //订单金额
    // wchtjeValide:true, //完成金额
    // tzjeValide:true, //调整金额
    compareABErr(array,prop1,prop2,prop2label,childKey){
      if (!array || !array.length) return
      if (!childKey) childKey = "children"
      for (let item of array) {
        console.log("做比较的两列",this.undefToZero(item[prop2]) , this.undefToZero(item[prop1]),item['wbsms'])
        if (this.undefToZero(item[prop2]) > this.undefToZero(item[prop1])){
          this.$message.error({
            dangerouslyUseHTMLString: true,
            message: `行：【${item['wbsms']}】</br>列：【${prop2label}】<br/>子节点和大于父节点值`,
            duration:5000
          });
          return  true ;
        }
        //console.error("做比较的两列",this.undefToZero(item[prop2]) , this.undefToZero(item[prop1]),item['wbsms'])

        if (item[childKey] && item[childKey].length) { //有children
          this.compareABErr(item[childKey],prop1,prop2,prop2label)
          // console.log("做比较的两列",this.undefToZero(item[prop2]) , this.undefToZero(item[prop1]),item['wbsms'])
        }else{
          if (this.undefToZero(item[prop2]) > this.undefToZero(item[prop1])){
            this.$message.error({
              dangerouslyUseHTMLString: true,
              message: `行：【${item['wbsms']}】</br>列：【${prop2label}】<br/>子节点和大于父节点值`,
              duration:5000
            });
            // return  false ;
          }
        }

      }
      // return true ;

    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }else if (column.property == 'estimate' || column.property == 'wchtje' || column.property == 'tzje'){ //订单金额 完成合同金额 调整金额
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else {
            sums[index] = 'N/A';
          }
          if (column.property == 'wchtje'){//完成合同金额 造价金额存到主表
            this.form.wchtje = sums[index]
          }
          if (column.property == 'zjqrje'){
            this.form.zjqrje = sums[index]
          }
        }else{
          sums[index] = '';
        }

      });
      //console.log("sums:",sums,sums[5],sums[4]);
       //工程形象进度
        if (!validatenull(sums[5]) &&  !validatenull(sums[4]) && sums[4]!=0){
          sums[8] = Math.round((sums[5] /sums[4])  * 10000 )  / 100
        }else{
          sums[8] =  '' ;
        }
     // console.log("----sums:",sums);
       return sums;
    },

    addMainTable(prop1,prop2,prop2label){ // estimate 订单金额 wchtje 完成合同金额 tzje 调整金额

      let flagItem = this.validateHaveNull(this.form.tableData,[])
      let msgStr = ''
      if(flagItem && flagItem.length>0){
        flagItem.forEach(item=>{
          msgStr =  msgStr + item.wbsms + ',' ;
          console.log("-----非空:item.id:"+item.id +'---'+ item.estimate)
        })
        msgStr = msgStr +  '【造价金额】不能为空'
        this.$message.error({
          dangerouslyUseHTMLString: true,
          message: msgStr,
          duration:5000
        });
        return ;
      }else{
        console.log("-----无非空:")
      }
      this.validateTree(this.form.tableData[0])

      //复制一列
      this.addCopyCol(this.form.tableData)
      //对复制的列'estimateCopy',重新计算用子节点的和覆盖父节点的值
      this.getNodeSum('estimateCopy')
      //加入验证列
      let estimateValideErr = this.compareABErr(this.form.tableData,'estimate','estimateCopy','订单金额') ;
      let wchtjeValideErr = this.compareABErr(this.form.tableData,'estimate','wchtje','合同金额') ;
     //let tzjeValideErr = this.compareABErr(this.form.tableData,'estimate','tzje','合同金额') ;
      console.log("-------estimateValideErr:",estimateValideErr)
      console.log("-------wchtjeValideErr:",wchtjeValideErr)
      //console.log("-------tzjeValideErr:",tzjeValideErr)

      // 开始验证整个树形结构
      // if (this.validateEntireTree(this.form.tableData)) {
      //   console.log("The tree is valid.");
      // } else {
      //   console.log("The tree is invalid.");
      // }

      // this.$refs.formRef.validate((valid) => {
      //   if (valid) {
      //     alert('submit!');
      //     console.log("----form:",this.form);
      //   } else {
      //     console.log('error submit!!');
      //     return false;
      //   }
      // });

    },
    validateTree(node) {
      let total = this.undefToZero(node.estimate); // 初始化总值为当前节点的值
      if (node.children && node.children.length > 0) {
        for (let child of node.children) {
          if (!this.validateTree(child)) { // 递归验证子节点
            return false; // 如果子节点验证失败，返回false
          }
          total +=  this.undefToZero(child.estimate); // 将子节点的值加到总和中
        }
      }
      if (total >  this.undefToZero(node.estimate)) { // 检查总和小于等于父节点值
        //console.error(`Node ${node.id} has a total value of ${total} which exceeds its own value ${node.estimate}`);
       // console.log('验证失败')
        return false; // 如果总和大，返回false
      }
      //console.log("验证成功")
      return true; // 验证成功，返回true
    },
    validatorCom(rule, value, callback,rowData,prop1,prop2,rowIndex,validatePropPrefix,tableForm){
      //console.log('----:',rule, value, callback,rowData)
      if (Number(rowData[prop1]) < Number(rowData[prop2])){
        callback('不合格数不能大于合格数')
      }else{
        callback()
        //清空rowIndex行的prop1和prop2单元格的验证
        this.$refs.formRef.clearValidate([`${validatePropPrefix}.${rowIndex}.${prop1}`,`${validatePropPrefix}.${rowIndex}.${prop2}`])
      }
    },
    undefToZero(val){
      if (validatenull(val)){
        return 0
      }else{
        return Number(val)
      }
    },
   //验证非空
    validateHaveNull(treeData,flagItem){
      if (!treeData || !treeData.length) return
      treeData.forEach((item) => {
        let a = validatenull(item['estimate'])
        if(a){
          flagItem.push(item)
        }
        if (item['children'] && item['children'].length) {
          this.validateHaveNull(item['children'],flagItem)
        }
      })
      return flagItem
    },


    validateEntireTree(nodes) {
      for (let node of nodes) {
        if (!validateTree(node)) {
          return false; // 如果任何一个节点验证失败，返回false
        }
      }
      return true; // 所有节点验证成功，返回true
    },

    getSum(data){
      if (!data) return ;
      let sum = 0 ;
      data.map(item=>{
        sum += !item.estimate ? 0 : Number(item.estimate);
      })
      return sum ;
    },
    calc(){

      this.form.tableData.map(item=>{
        this.calculateParentAmount(item)
      })
    },
    calculateParentAmount(node) {
      // 如果没有子节点，直接返回当前节点的 amount（叶子节点）
      if (!node.children || node.children.length === 0) {
        return this.undefToZero(node.amount);
      }

      // 递归计算所有子节点的 amount 总和
      let total = 0;
      for (const child of node.children) {
        total += this.calculateParentAmount(child);
      }

      // 将父节点的 amount 更新为子节点总和
      node.amount = total;
      return total;
    },

  }
}
</script>

<style scoped>

</style>
